package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;
import com.qf.vo.PermVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 更新角色的权限
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.02.22
 * @since 1.0
 */
@RestController
@RequestMapping("/admin/role")
@Slf4j
public class DtsAdminRoleController {

    @Autowired
    DtsRoleService roleService;

    @Autowired
    ApplicationContext context;

    @Autowired
    DtsPermissionService permissionService;

    @PostMapping("/permissions")
    public  Object updatePermissions(@RequestBody Map<String,Object> map){
        log.info(map + "");
        Integer roleId = (Integer) map.get("roleId");
        List<String> permissions = (List<String>) map.get("permissions");
//        System.out.println(roleId);
//        System.out.println(permissions);

        //如果是超级管理员，提示拒绝修改权限
        if(roleService.checkIsSuperManager(roleId)){
            return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
        }
        //如果不是超级管理员，则修改权限
        roleService.updatePermissions(roleId,permissions);
        return ResponseUtil.ok();
    }

    @GetMapping("/permissions")
    public Object getPermissions(Integer roleId){
        //获取系统权限：解析controller 中的每个方法上的 注解，获取系统权限
        List<Permission> permissions = PermissionUtil.listPermission(context, "com.qf.controller");
        List<PermVo> permVos = PermissionUtil.listPermVo(permissions);

        Set<String> permsString = null;

        //获取角色拥有的权限
        //1.是否是超级管理员，如果是超级管理员，则包括所有的系统权限
        if(roleService.checkIsSuperManager(roleId)){
            permsString = PermissionUtil.listPermissionString(permissions);
        }
        //2.如果不是超级管理员，根据角色查询相应的权限
        else{
            permsString =  permissionService.findPermsByRoleIds(new Integer[]{roleId});
        }

        Map<String,Object> data = new HashMap<>();
        //系统权限
        data.put("systemPermissions",permVos);
        //该角色拥有的权限
        data.put("assignedPermissions",permsString);
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:role:delete")
    @RequiresPermissionsDesc(menu = { "系统管理", "角色管理" }, button = "角色删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsRole role){
        log.debug("role--delete:{"+ role +"}");

        //判断是否被关联
        if(roleService.checkRelationRole(role.getId())){
            roleService.deleteById(role.getId());

            log.info("删除角色成功");

            return ResponseUtil.ok();

        }
        return AdminResponseUtil.fail(640,"角色不能被删除");

    }

    @RequiresPermissions("admin:role:update")
    @RequiresPermissionsDesc(menu = { "系统管理", "角色管理" }, button = "角色编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsRole role){
        log.debug("role --update:{"+ role +"}");

        DtsRole dd = roleService.update(role);

        log.info("修改角色成功");
        return ResponseUtil.ok(dd);
    }


    @RequiresPermissions("admin:role:create")
    @RequiresPermissionsDesc(menu = { "系统管理", "角色管理" }, button = "角色添加")
    @PostMapping("/create")
    public Object create(@RequestBody DtsRole role){
        //判断角色是否重复: 找到返回true ,找不到返回false
       boolean  flag =  roleService.checkRole(role.getName());
        if (flag) {
            return AdminResponseUtil.fail(AdminResponseCode.ROLE_NAME_EXIST);
        }

       DtsRole role1 =  roleService.insert(role);

       return ResponseUtil.ok(role1);
    }

    @RequiresPermissions("admin:role:list")
    @RequiresPermissionsDesc(menu = { "系统管理", "角色管理" }, button = "角色查询")
    @GetMapping("/list")
    public Object list(
            @RequestParam(value = "page",defaultValue = "1") Integer page ,
            @RequestParam(value = "limit",defaultValue = "10") Integer limit , String sort, String order ,String rolename){
        IPage<DtsRole> iPage = roleService.queryPage(page,limit,sort,order,rolename);

        Map<String,Object> data = new HashMap<>();

        data.put("items",iPage.getRecords());
        data.put("total",iPage.getTotal());

        return ResponseUtil.ok(data);
    }

    @GetMapping("/options")
    public Object findAll(){
       List<DtsRole> roles = roleService.findAll();

      List<Map<String,Object>> data =  roles.stream().map(role ->{
           Map<String,Object> map = new HashMap<>();
           map.put("value",role.getId());
           map.put("label",role.getName());
           return map;
       }).collect(Collectors.toList());
      return ResponseUtil.ok(data);
    }
}
